package com.example.ch05_springboot_web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Locale;

@RestController
@RequestMapping("/greet")
public class GreetingController {

    @Autowired
    private MessageSource messageSource;

    static final Logger log = LoggerFactory.getLogger(GreetingController.class);

    /**
     *  http://localhost:8088/greet?lang=en_US
     * @param lang
     * @return
     */
    @GetMapping
    public String greet(@RequestParam(name = "lang", required = false) String lang) {
        // 当前请求的语言环境
        Locale locale = LocaleContextHolder.getLocale();
        // 根据请求的语言环境来获取国际化配置信息
        String loginUserName = messageSource.getMessage("greeting", null, locale);
        log.info("Local={}, loginUserName={}", locale, loginUserName);

        Locale locale2 = lang != null ? new Locale(lang) : Locale.getDefault();

        return messageSource.getMessage("greeting", null, locale2);
    }
}
